<template>
  <div class="doc-container">
    <div style="flex: 1;width: 100%;">
      <el-card shadow="never">
      <div slot="header" style="display: flex;align-items: center;justify-content: space-between;height: 50px;">
          <n-title title="文档智脑" />
          <div class="compact-upload">
            <el-upload
              class="upload-demo"
              :multiple="false"
              :show-file-list="false"
              :before-upload="beforeUpload"
              :http-request="handleUpload"
            >
              <el-button 
                type="primary" 
                icon="el-icon-upload"
                class="upload-btn"
              >
                点击上传文档
              </el-button>
              <!-- <div class="el-upload__tip" slot="tip">
                支持格式：doc/docx/pdf，最大20MB
              </div> -->
            </el-upload>
        </div>
       </div>
       <el-row :gutter="20" class="file-list">
      <el-col 
        v-for="file in fileList"
        :key="file.id"
        :xs="24" 
        :sm="12" 
        :md="8" 
        :lg="6"
        class="file-item"
      >
        <el-card class="file-card" shadow="hover">
          <!-- 缩略图区域 -->
          <div class="thumbnail" @click="handlePreview(file)">
            <img 
              v-if="['pdf', 'doc', 'docx','xlsx','xls'].includes(file.fileType)"
              :src="getThumbnail(file.fileType)"
              class="document-thumbnail"
            >
            <div v-else class="file-type-icon">
              <i :class="file.thumbnail || 'el-icon-document'"></i>
              <span class="format-text">{{ getFileType(file.fileName) }}</span>
            </div>
          </div>
          
          <!-- 文件信息 -->
          <div class="file-info">
            <div class="file-name" :title="file.fileName">{{ file.fileName }}</div>
            <div class="file-meta">
              <span class="file-size">{{ formatFileSize(file.fileSize) }}</span>
              <el-divider direction="vertical"></el-divider>
              <span class="upload-time">{{ file.uploadTime }}</span>
            </div>
          </div>

          <!-- 操作按钮 -->
          <div class="file-actions">
            <el-tooltip content="下载" placement="top">
              <el-button 
                type="primary" 
                icon="el-icon-download" 
                circle
                @click="handleDownload(file)"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button 
                type="danger" 
                icon="el-icon-delete" 
                circle
                @click="handleDelete(file)"
              ></el-button>
            </el-tooltip>
          </div>
        </el-card>
      </el-col>
    </el-row>
    </el-card>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import { ElUploadInternalRawFile } from 'element-ui/types/upload';
import { Message } from 'element-ui';
import {deleteDocuments,findAll,uploadDocuments} from '@/api/documents'
import NTitle from "@/components/NTitle.vue";

interface FileItem {
  id: string;
  fileName: string;
  fileSize: number;
  url: string;
  uploadTime: string;
  fileType: 'doc' | 'docx' | 'pdf' | 'other';
  thumbnail?: any;
  mongoFileId:string;
}
@Component({
  methods: {},
  components: {NTitle }
})
export default class docLibrary extends Vue {
  private fileList:any = [];

  // 获取文件类型图标
  private getFileIcon(filename: string): string {
    const ext = filename.split('.').pop()?.toLowerCase() || '';
    switch(ext) {
      case 'pdf': return 'el-icon-document-pdf';
      case 'doc': 
      case 'docx': return 'el-icon-document-word';
      default: return 'el-icon-document';
    }
  }

  // 其他方法保持与之前实现一致，只需新增缩略图处理方法...
  
    // 上传处理
    private async handleUpload(options: any) {
    try {
      const formData = new FormData();
      formData.append('file', options.file);
      
      const res = await uploadDocuments(formData);
      this.fileList = [res.data, ...this.fileList];
      Message.success('上传成功');
    } catch (error) {
      Message.error('上传失败');
    }
  }

  private getFileType(filename: string): string {
    const ext = filename.split('.').pop()?.toLowerCase() || '';
    if (['doc', 'docx'].includes(ext)) return 'Word';
    if (ext === 'pdf') return 'PDF';
    if (['xlsx', 'xls'].includes(ext)) return 'Excel';
    return '未知格式';
  }

  private getThumbnail(fileType: string): string {
  const images = {
    pdf: require('@/assets/image/pdf_icon_256.png'),
    doc: require('@/assets/image/word_icon_256.png'),
    docx: require('@/assets/image/word_icon_256.png'),
    xlsx: require('@/assets/image/excel_icon_256.png'),
    xls: require('@/assets/image/excel_icon_256.png'),
    ppt: require('@/assets/image/ppt_icon_256.png'),
    paper: require('@/assets/image/paper_icon_256.png')
  };
  return images[fileType as keyof typeof images] || images['paper'];
}

  private formatFileSize(size: number): string {
    if (size === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(size) / Math.log(k));
    return parseFloat((size / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  }

  private beforeUpload(file: ElUploadInternalRawFile): boolean {
    return true;
    // const isValidType = ['application/pdf', 'application/msword', 
    //   'application/vnd.openxmlformats-officedocument.wordprocessingml.document']
    //   .includes(file.type);
    // const isValidSize = file.size / 1024 / 1024 < 20;

    // if (!isValidType) {
    //   Message.error('只支持上传 PDF/Word 格式文件!');
    //   return false;
    // }
    // if (!isValidSize) {
    //   Message.error('文件大小不能超过 20MB!');
    //   return false;
    // }
    // return true;
  }


  // 删除文档
  private async handleDelete(row: FileItem) {
    try {
      await this.$confirm('确定删除该文件吗？', '提示', { type: 'warning' });
      await deleteDocuments({ id: row.id });
      this.fileList = this.fileList.filter(file => file.id !== row.id);
      Message.success('删除成功');
    } catch (error) {
      console.error(error);
      // 取消删除不处理
    }
  }

  // 下载文件
  // 下载文档
  private async handleDownload(row: FileItem) {
    try {

      const link = document.createElement('a');
      link.href = process.env.VUE_APP_BASE_API +'/resources/file/' + row.mongoFileId;
      link.setAttribute('download',row.fileName);
      link.click();
      document.body.appendChild(link);
    } catch (error) {
      Message.error('下载失败'+error);
    }
  }


  private async handlePreview(row: FileItem) {
  try {
    const fileType = this.getFileExtension(row.fileName);
    
    if (fileType === 'pdf') {
       window.open(`${process.env.VUE_APP_BASE_API}/resources/file/${row.mongoFileId}`);
    } else if (fileType === 'docx') {
      this.$message.info("目前无法预览");
    } else if (fileType === 'doc') {
      this.$message.info("目前无法预览");
    }
  } catch (error) {
    this.$message.error('预览失败: ' + (error as Error).message);
  }
}
private getFileExtension(filename: string): string {
  return filename.split('.').pop()?.toLowerCase() || '';
}

  // 组件挂载时加载数据
  mounted() {
    this.loadDocuments();
  }

  // 加载文档列表
  private async loadDocuments() {
    try {
      const res = await findAll();
      this.fileList = await Promise.all(
        res.data.map(async (file) => ({
          ...file,
          thumbnail: await this.generateThumbnail(file)
        }))
      );
    } catch (e) {
      console.log(e)
      Message.error('获取文档列表失败');
    }
  }

  // 生成缩略图
   async generateThumbnail(file): Promise<string> {
    try {
      
      if (file.fileType === 'pdf') {
        return 'pdf-thumbnail';
      } else if (['doc', 'docx'].includes(file.fileType)) {
        return 'word-thumbnail';
      }
      return 'el-icon-document';
    } catch (error) {
      console.error('缩略图生成失败:', error);
      return 'el-icon-document';
    }
  }

  // 生成PDF缩略图
  // private async generatePdfThumbnail(url: string): Promise<string> {
    
  //   const pdf = PDFJS.getDocument({
  //     url: url,
  //     disableWorker: true // 禁用web worker
  //   }).promise;

  //   const page = await pdf.getPage(1);
    
  //   const viewport = page.getViewport({ scale: 0.5 });
  //   const canvas = document.createElement('canvas');
  //   const context = canvas.getContext('2d')!;
    
  //   canvas.height = viewport.height;
  //   canvas.width = viewport.width;
    
  //   await page.render({
  //     canvasContext: context,
  //     viewport: viewport
  //   }).promise;
    
  //   return canvas.toDataURL();
  // }

  // 生成Word文档缩略图
  // private async generateDocThumbnail(url: string): Promise<string> {
  //   const response = await fetch(url);
  //   const arrayBuffer = await response.arrayBuffer();
    
  //   const { value: html } = await mammoth.convertToHtml({ arrayBuffer });
  //   const parser = new DOMParser();
  //   const doc = parser.parseFromString(html, 'text/html');
    
  //   // 提取前3个段落
  //   const content = Array.from(doc.body.children)
  //     .slice(0, 3)
  //     .map(el => el.outerHTML)
  //     .join('');
    
  //   return `
  //     <div class="doc-preview">
  //       <div class="doc-content">${content}</div>
  //       <div class="watermark">DOC Preview</div>
  //     </div>
  //   `;
  // }
}
</script>

<style lang="scss" scoped>
.doc-container {

  margin: 0px 10px;
  padding: 0px;
}

.file-list {
  margin-top: 30px;
}

.file-card {
  margin-bottom: 20px;
  transition: transform 0.3s;

  &:hover {
    transform: translateY(-5px);
  }

  .thumbnail {
    height: 180px;
    background: #f5f7fa;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    position: relative;
    overflow: hidden;

    .document-thumbnail {
      max-width: 100%;
      max-height: 100%;
      object-fit: contain;
    }

    .file-type-icon {
      text-align: center;
      i {
        font-size: 64px;
        color: #409EFF;
      }
      .format-text {
        display: block;
        color: #666;
        margin-top: 10px;
      }
    }
  }

  .file-info {
    padding: 15px 0;

    .file-name {
      font-weight: bold;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .file-meta {
      margin-top: 8px;
      font-size: 12px;
      color: #909399;
      display: flex;
      align-items: center;
      
      .el-divider {
        background-color: #dcdfe6;
        margin: 0 8px;
      }
    }
  }

  .file-actions {
    display: flex;
    justify-content: space-around;
    padding: 10px 0;
    border-top: 1px solid #ebeef5;
  }
}

.compact-upload {
  height: 50px;
  display: flex;
  align-items: right;
  justify-content: left;
  margin: 20px 0;
  position: relative;

  ::v-deep .el-upload {
    width: auto;
    height: 100%;
    display: flex;
    align-items: center;
  }

  .upload-btn {
    height: 40px;
    padding: 0 25px;
    border-radius: 20px;
    font-size: 14px;
    
    i {
      margin-right: 8px;
    }
  }

  .el-upload__tip {
    position: absolute;
    bottom: -22px;
    left: 50%;
    transform: translateX(-50%);
    white-space: nowrap;
    font-size: 12px;
    color: #909399;
  }
}
.pdf-thumbnail{

}
.word-thumbnail{

}
@media (max-width: 768px) {
  .file-card {
    .thumbnail {
      height: 120px;
      .file-type-icon i {
        font-size: 48px;
      }
    }
  }
}
</style>